package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.ProjectManage;
import com.ruoyi.system.domain.ProjectManageDetail;
import com.ruoyi.system.domain.vo.ProjectManageCreateReqVO;
import com.ruoyi.system.domain.vo.ProjectManageRespVO;
import com.ruoyi.system.mapper.ProjectManageMapper;
import com.ruoyi.system.service.IProjectManageDetailService;
import com.ruoyi.system.service.IProjectManageService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-01
 */
@Service
public class ProjectManageServiceImpl extends ServiceImpl<ProjectManageMapper, ProjectManage> implements IProjectManageService {
    @Resource
    private ProjectManageMapper projectManageMapper;

    @Resource
    private IProjectManageDetailService projectManageDetailService;

    @Resource
    private ISysUserService iSysUserService;

    /**
     * 查询项目管理
     *
     * @param id 项目管理主键
     * @return 项目管理
     */
    @Override
    public ProjectManageRespVO selectProjectManageById(Long id) {
        ProjectManage projectManage = projectManageMapper.selectById(id);
        ProjectManageRespVO respVO = new ProjectManageRespVO();
        if (projectManage != null) {
            respVO.setId(projectManage.getId());
            respVO.setName(projectManage.getName());
            List<Long> userIds = Arrays.stream(projectManage.getUserIds().split("/")).map(Long::parseLong).collect(Collectors.toList());
            respVO.setUserIds(userIds);
            respVO.setUserNames(projectManage.getUserNames());
            respVO.setCreateName(projectManage.getCreateName());
        }
        return respVO;
    }

    /**
     * 查询项目管理列表
     *
     * @param projectManage 项目管理
     * @return 项目管理
     */
    @Override
    public List<ProjectManage> selectProjectManageList(ProjectManage projectManage) {
        return projectManageMapper.selectProjectManageList(projectManage);
    }

    /**
     * 新增项目管理
     *
     * @param reqVO 项目管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProjectManage(ProjectManageCreateReqVO reqVO) {

        if (CollUtil.isEmpty(reqVO.getUserIds())) {
            throw new ServiceException("请选择项目接收人！");
        }
        // 项目名称校验
        LambdaQueryWrapper<ProjectManage> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ProjectManage::getName, reqVO.getName());
        lqw.last("limit 1");
        if (projectManageMapper.selectOne(lqw) != null) {
            throw new ServiceException("项目名称已存在！");
        }

        ProjectManage projectManage = new ProjectManage();
        projectManage.setId(idUtil());
        projectManage.setName(reqVO.getName());
        Long userId = SecurityUtils.getUserId();
        projectManage.setCreateBy(userId.toString());
        projectManage.setUpdateBy(userId.toString());
        projectManage.setCreateTime(DateUtils.getNowDate());
        projectManage.setUpdateTime(DateUtils.getNowDate());
        SysUser createUser = iSysUserService.selectUserById(userId);
        if (createUser != null){
            projectManage.setCreateName(createUser.getNickName());
        }

        List<String> userIds = new ArrayList<>();
        List<String> userNames = new ArrayList<>();

        List<ProjectManageDetail> saveBatchList = reqVO.getUserIds().stream().map(userid -> {
            ProjectManageDetail projectManageDetail = new ProjectManageDetail();
            projectManageDetail.setProjectManageId(projectManage.getId());
            projectManageDetail.setProjectManageName(projectManage.getName());

            SysUser sysUser = iSysUserService.selectUserById(userid);
            if (sysUser != null) {
                userIds.add(userid.toString());
                projectManageDetail.setUserId(userid);

                userNames.add(sysUser.getNickName());
                projectManageDetail.setUserName(sysUser.getNickName());
            }
            projectManageDetail.setCreateBy(projectManage.getCreateBy());
            projectManageDetail.setCreateTime(projectManage.getCreateTime());
            projectManageDetail.setUpdateBy(projectManage.getUpdateBy());
            projectManageDetail.setUpdateTime(projectManage.getUpdateTime());
            projectManageDetail.setCreateName(projectManage.getCreateName());
            //数据库状态默认未完成
            return projectManageDetail;
        }).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(userIds)) {
            projectManage.setUserIds(String.join("/", userIds));
            projectManage.setUserNames(String.join("/", userNames));
        }
        projectManageDetailService.saveBatch(saveBatchList);
        projectManageMapper.insert(projectManage);
        return 1;
    }

    public Long idUtil() {
        return IdUtil.getSnowflake(1, 1).nextId();

    }

    /**
     * 修改项目管理
     *
     * @param reqVO 项目管理
     * @return 结果
     */
    @Override
    public int updateProjectManage(ProjectManageCreateReqVO reqVO) {
        reqVO.setUpdateTime(DateUtils.getNowDate());
        //return projectManageMapper.updateProjectManage(null);
        return 1;
    }

    /**
     * 批量删除项目管理
     *
     * @param ids 需要删除的项目管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProjectManageByIds(Long[] ids) {
        projectManageDetailService.deleteProjectManageDetailByProjectManageIds(Arrays.asList(ids));
        return projectManageMapper.deleteProjectManageByIds(ids);
    }

    /**
     * 删除项目管理信息
     *
     * @param id 项目管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProjectManageById(Long id) {
        projectManageDetailService.deleteProjectManageDetailByProjectManageIds(CollUtil.newArrayList(id));
        return projectManageMapper.deleteProjectManageById(id);
    }
}
